package service

import (
	"gitee.com/crack007/goose"
	"github.com/crack007/go-im/src/common/constant"
	"github.com/crack007/go-im/src/common/model"
	"sync"
)

type nodeService struct {
	nodeMap sync.Map
	lock    sync.Mutex
}

func (s *nodeService) Add(nodeModel *model.NodeModel) {
	goose.GetLogger().Debug("node add->%s address:%s grpc:%d", nodeModel.Id, nodeModel.Ip, nodeModel.Port)
	s.nodeMap.Store(nodeModel.Id, nodeModel)
}

func (s *nodeService) Get(nodeName string) *model.NodeModel {
	if v, ok := s.nodeMap.Load(nodeName); ok {
		return v.(*model.NodeModel)
	}
	return nil
}

func (s *nodeService) List() map[string]*model.NodeModel {
	var list = make(map[string]*model.NodeModel)
	s.nodeMap.Range(func(key, value interface{}) bool {
		list[key.(string)] = value.(*model.NodeModel)
		return true
	})
	return list
}

func (s *nodeService) Remove(nodeName string) {
	goose.GetLogger().Debug("node remove->%s", nodeName)
	s.nodeMap.Delete(nodeName)
}

func (s *nodeService) Store(nodeModel *model.NodeModel) {
	RedisService.GetRedis().SAdd(constant.WsWorkerList, nodeModel.String())
}
func (s *nodeService) RemoveCache(nodeModel *model.NodeModel) {
	RedisService.GetRedis().SRem(constant.WsWorkerList, nodeModel.String())
}
